package cron

import (
	"time"

	"git.oschina.net/gunsluo/hawkeye-common/g"
	"git.oschina.net/gunsluo/hawkeye-common/model"
)

var mfs []model.FuncsAndInterval

func Mappers(mappers []model.FuncsAndInterval) {
	mfs = mappers
}

/*
	Description: 函数功能
	1、采集监控数据

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func Collect() {

	if !g.Config().Agent.Enabled {
		return
	}

	if g.Config().Agent.Addr == "" {
		return
	}

	for _, v := range mfs {
		go collect(int64(v.Interval), v.Fs)
	}
}

/*
	Description: 函数功能
   	1、定时执行
   	2、循环采集
   	3、上报数据

	Author: jerrylou, <gunsluo@gmail.com>
	Since:  2016/08/25
*/
func collect(sec int64, fns []func() []*model.MetricValue) {

	t := time.NewTicker(time.Second * time.Duration(sec)).C
	for {
		<-t

		hostname, err := g.Hostname()
		if err != nil {
			continue
		}

		mvs := []*model.MetricValue{}

		// 循环执行采集接口函数 2016/08/25 Add by jerrylou
		for _, fn := range fns {
			items := fn()
			if items == nil {
				continue
			}

			if len(items) == 0 {
				continue
			}

			for _, mv := range items {
				mvs = append(mvs, mv)
			}
		}

		now := time.Now().Unix()
		for j := 0; j < len(mvs); j++ {
			mvs[j].Step = sec
			mvs[j].Endpoint = hostname
			mvs[j].Timestamp = now
		}

		// 采集数据发送给agent 2016/08/25 Add by jerrylou
		g.SendToAgent(mvs)
	}
}
